package com.zhyl.demo.utils;

import com.zhyl.demo.entity.Specialty;

import java.util.ArrayList;
import java.util.List;

public class menuTree {

    // 流程：数据库查出的菜单记录装载在承载菜单的列表中---
    //         构建树（获取根节点，遍历根节点，对每一个根节点构建子树）---得到最终树形菜单

    // 承载菜单的列表
    private List<Specialty> SpecialtyList = new ArrayList<>();
    // 带参构造器，将数据库中的菜单数据记录，装载在我们承载菜单的列表中
    public menuTree(List<Specialty> SpecialtyList){
        this.SpecialtyList = SpecialtyList;
    }

    // 获取根节点
    public List<Specialty> getRootNode(){
        List<Specialty> rootNode = new ArrayList<>();
        for (Specialty Specialty : SpecialtyList) {
            if (Specialty.getXid()==0){
                rootNode.add(Specialty);
            }
        }
        return rootNode;
    }

    // 构建子树
    public Specialty buildChildren(Specialty rootNode){
        List<Specialty> childrenTree = new ArrayList<>();
        for (Specialty Specialty : SpecialtyList) {
            if (Specialty.getXid()==rootNode.getId()){
                childrenTree.add(buildChildren(Specialty));
            }
        }
        rootNode.setChild(childrenTree);
        return rootNode;
    }

    // 构建树
    public List<Specialty> buildTree(){
        List<Specialty> Specialtys = getRootNode();
        for (Specialty Specialty : Specialtys) {
            buildChildren(Specialty);
        }
        return Specialtys;
    }
}